import { createRouter, createWebHashHistory } from "vue-router";
import { RouterTy } from "@/types/router";
import { generateRoute } from '@/utils/utils';
import { queryUserPermissions } from '@/api/user'
const routes: RouterTy = [
  {
    path: "/",
    name: "main",
    meta: {
      title: "基础模板",
    },
    component: () => import("../views/Main/index.vue"),
    redirect: "/home",
    children: [
      {
        path: "/home",
        name: "Home",
        meta: {
          title: "首页",
        },
        component: () => import("../views/Home/index.vue"),
      },
      {
        path: "/frame/:url",
        name: "Frame",
        meta: {
          title: "外部链接",
        },
        component: () => import("../views/Frame/index.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    meta: {
      title: "登录",
    },
    component: () => import("../views/Login/index.vue"),
  },
  {
    path: "/404",
    name: "404",
    meta: {
      title: "页面未找到",
    },
    component: () => import("../views/404.vue"),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

async function loadRoutes() {
  const token = localStorage.getItem('accessToken');
  if (token) {
    try {
      const { data } = await queryUserPermissions({})
      let routes = generateRoute(data)
      routes.map((route: any) => {
        let _component = route.component
        route.component = () => import(`./../views/${_component}/index.vue`)
        router.addRoute("main", route);
      })
    } catch (error) {

    }
  }
}

await loadRoutes();

router.beforeEach((to, from, next) => {
  console.log("路由beforeEach",from);
  document.title = `${to.meta.title} | EVA-admin`;
  if (router.hasRoute(to?.name || 'noRoute')) {
    next()
  } else {
    next('/404')
  }
});

export default router;
